package cjyyp.day02;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class Reebtrantlock锁的Condition {
    static ReentrantLock reentrantLock=new ReentrantLock();
    //送外卖的休息室
    static Condition condition1=reentrantLock.newCondition();
    static boolean flag1;
    //送烟的休息室
    static Condition condition2=reentrantLock.newCondition();
    static boolean flag2;

    public static void main(String[] args) throws InterruptedException {
        //需要吃外卖才能工作的线程
        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                log.debug("我是准备吃外卖工作才的线程");
                reentrantLock.lock();
                while (!flag1){
                    log.debug("没外卖，不工作了");
                    try {
                        condition1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("我被唤醒，吃外卖工作了");
                reentrantLock.unlock();
            }
        });

        //需要抽烟才能工作的线程
        Thread t2=new Thread(new Runnable() {
            @Override
            public void run() {
                log.debug("我是准备抽烟工作才的线程");
                reentrantLock.lock();
                while (!flag2){
                    log.debug("没烟抽，不工作了");
                    try {
                        condition2.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("我被唤醒，抽烟工作了");
                reentrantLock.unlock();
            }
        });

        t1.start();
        t2.start();

        Thread.sleep(2000);
        //送烟
        smoke();

        //送外卖
        takeout();

    }
    static private void smoke() throws InterruptedException {
        reentrantLock.lock();
        Thread.sleep(1000);
        log.debug("我是主线程：我去送烟了");
        flag2=true;
        condition2.signal();
        reentrantLock.unlock();
    }

    static private void takeout() throws InterruptedException {
        reentrantLock.lock();
        Thread.sleep(2000);
        log.debug("我是主线程：我去送外卖了");
        flag1=true;
        condition1.signal();
        reentrantLock.unlock();
    }

}
